import 'package:flutter/material.dart';
import 'package:flutter_provider_demo/shopping/model/shopping_provider.dart';

class ShoppingCartProvider extends ChangeNotifier {
  ShoppingProvider _shoppingProvider;

  final List<int> _itemIds = [];

  ShoppingProvider get shoppingProvider => _shoppingProvider;

  set shoppingProvider(ShoppingProvider newShoppingProvider) {
    assert(newShoppingProvider != null);
    assert(_itemIds.every((id) => newShoppingProvider.getById(id) != null));

    _shoppingProvider = newShoppingProvider;

    notifyListeners();
  }

  //通过id获取购物车列表
  List<Item> get items =>
      _itemIds.map((id) => _shoppingProvider.getById(id)).toList();

  //通过购物车列表获取总价
  int get totalPrice =>
      items.fold(0, (previousValue, element) => previousValue + element.price);

  //加入购物车
  void add(Item item) {
    _itemIds.add(item.id);
    notifyListeners();
  }

  //移除购物车
  void remove(Item item) {
    _itemIds.remove(item.id);
    notifyListeners();
  }
}
